<#import "/spring.ftl" as spring />
<#import "../layout/defaultLayout.ftl" as layout>
<@layout.defaultLayout styles=["bootstrap-table/bootstrap-table.min.css",
"bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css"]
scripts=["bootstrap-table/bootstrap-table.min.js",
"bootstrap-table/locale/bootstrap-table-zh-CN.min.js",
"bootstrap-validator/validator.js",
"jquery/serializejson/jquery.serializejson.min.js",
"util/jquery-dateFormat.min.js",
"bootstrap-table/extensions/export/bootstrap-table-export.min.js",
"bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js",
"bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js",
"chart/Chart.bundle.js","js/chart.js",
"util/tableExport.js"]>
<style>
canvas {
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}
.chartDiv {
	border: 2px solid #ededed;
	border-radius: 10px;
	float: left;
	margin: 2 auto;
	min-width: 310px;
	background-color: white;
	height: 100%;
	margin-left: 0.5%;
	margin-top: 0.5%;
	padding: 1%;
	-webkit-border-top-left-radius: 10px;
	-webkit-border-top-right-radius: 10px;
	-webkit-border-bottom-right-radius: 10px;
	-webkit-border-bottom-left-radius: 10px
}

#container_bar {
	width: 66%;
}

#container_line {
	width: 66%;
}

#container_pie {
	width: 33%;
}
#container_button {
	width: 33%;
}
table td, table th {
    min-width: 100px;
}
</style>
<div class="container-fluid">
        <div class="container">
         	 	<form class="form-inline" role="form" id="queryForm">
         	 	<input type="text" id ="reportId" name="reportId" value="${reportId}" style="display:none">
         	 	<!-- <a  data-toggle="modal" data-target="#myModal" style="cursor:pointer;">
            		Launch modal table
        		</a> -->
                    <div>
                        <div id="main-toolbar">
			        
			          <#list reportCondition as condition>
			          	<#if condition?index%4 == 0 && condition?index != 0>
			          		<div class="col-sm-3 col-md-3">
			          	</#if>
			          	<#if condition.type == '1'>

							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" class="form-control" id="${condition.code}" name="${condition.code}"/>
							  </div>
				          <#elseif condition.type == '2'>
							   <div class="form-group">
							    <label for="${condition.code}">${condition.name}</label>
							    <input type="text" id="${condition.code}" value ="" name="${condition.code}" class ="form-control datetimepicker"  />
							  </div>
						  <#elseif condition.type == '3'>

				          	 <div class="form-group">
					          <label class="control-label" for="${condition.code}">${condition.name}</label>
					            <select class="form-control" id="${condition.code}" name="${condition.code}">
					            	<option value=""><@spring.message "select.tip"/></option>
						  		<#if condition.comboboxType == 1>						  			
						  			<#list enumList as obj>
						  				<#if obj.condition.id == condition.id>
						  					<option value="${obj.code}">${obj.name}</option>
						  				</#if>
						  			</#list>
						  		<#elseif condition.comboboxType == 2>	
						  			<#if condition.cascadeCondition??>
							  			<option class="hideOption" style="display:none;" name="${condition.cascadeCondition}" code="${condition.code}"></option>
							  		<#else>
							  			<#list conditionValList as conditionVal>
							  				<#if condition.id == conditionVal.conditionId>
							  					<option value="${conditionVal.code}">${conditionVal.name}</option>
							  				</#if>
							  			</#list>
							  		</#if>
						  		</#if>
				          		</select>		
						        </div>
				          </#if>
				          <#if condition?index%4 - 3 == 0 && condition?index != 0>
			          		</div>
			          	 </#if>
			          </#list>
			          <#if reportCondition?size gt 0 >
			        	 <button id="queryByCondition" type="button" class="btn btn-success" ><@spring.message "button.submit" /></button>
					 </#if>
					 <button id="exportExcel" type="button" class="btn btn-success" ><@spring.message "button.export" /></button>
			      </div>
				   
				  </form>
            <div>
                <table id="mainTable" data-classes="table table-hover table-striped" 
                	data-toolbar="#main-toolbar" data-toggle="table"
				           data-pagination="true"
				           data-page-list="[10,20]"
				           data-side-pagination="server"
				           data-content-type ="application/json"
				           data-data-type = "json"
				           data-query-params-type="limit"
				           data-method = "post"
				           data-show-footer="true"
				           data-response-handler="responseHandler"
				           data-query-params ="queryParams">

                </table>

            </div>
            <!-- （Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog" style="width:1000px;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
					&times;
				</button>
				<h4 class="modal-title" id="myModalLabel">
					
				</h4>
			</div>
			<div class="modal-body">
				<table id="modelTable" data-classes="table table-hover table-striped" data-toggle="table" data-pagination="true"
						   data-toolbar="#drillToolbar" data-toolbar-align="right"
				           data-page-list="[10,20]"
				           data-side-pagination="server"
				           data-content-type ="application/json"
				           data-data-type = "json"
				           data-show-footer="true"
				           data-query-params-type="limit"
				           data-method = "post"
				           data-response-handler="responseDrillHandler"
				           data-query-params ="queryDrillParams">

                </table>
                <div id="drillToolbar">
                	<button id="exportDrillExcel" type="button" class="btn btn-success" ><@spring.message "button.export"/></button>
                </div>
			</div>	
			<div class="modal-footer">
				<button type="button" class="btn btn-default" data-dismiss="modal"><@spring.message "button.shutdown"/>
				</button>
			</div>
		</div><!-- /.modal-content -->
	</div><!-- /.modal -->
</div>
        </div>
        

</div>

<div style="border: 0px; width: 100%">
		<div id="container_bar" hidden="true" class="chartDiv">
			<canvas id="canvas_bar"></canvas>
		</div>
		<div id="container_pie" hidden="true" class="chartDiv">
			<canvas id="canvas_pie" style="margin: 5px"></canvas>
		</div>
		<div id="container_line" hidden="true" class="chartDiv">
			<canvas id="canvas_line"></canvas>
		</div>
		<!-- <div style="margin-top: 0.5%;margin-right: 0.5%;text-align: right; float: right;" ><button onclick="toList();" class="btn btn-success" style="width: 100px;">确定</button></div>
		 -->
	</div>
		
	
<script>	
    var mTable = $('#mainTable');
    var columns = [], datas = [], drillColumns = [];
    var flag = 0;
    var modelTable =  $('#modelTable');
    var linkItem = null;//有链接报表的字段数组
    var reportId = $("#reportId").val();
    var drillRequestObj = null;//点击字段传参
    $('.datetimepicker').datetimepicker({
	    format: 'yyyy-mm-dd hh:ii:ss',
	    autoclose: true,
        todayBtn: true,
        todayHighlight:true,
        language:'zh-CN'
	});
	
	$("#queryByCondition").click(function(){
		datas = [];
		//queryData();
		freshData();
	
	});
	
	$("#exportExcel,#exportDrillExcel").click(function(){
		var exportObj = $('#queryForm').serializeJSON();
		location.href="/report/exportExcel?paramStr="+JSON.stringify(exportObj);  
		/* $.ajax({
	        url:'/report/exportExcel',
	        type:'post',
	        contentType: 'application/json',
	        data:JSON.stringify(exportObj),
	        dataType:'json',
	        success:function(data){
	        	
	        }
		}); */
	});
	
	function queryParams(params) {
		var mainObj = $('#queryForm').serializeJSON();
		mainObj.offset = params.offset;
		mainObj.limit = params.limit;
		return mainObj;
	}
	function queryDrillParams(params) {
		
		var paramObj = drillRequestObj;
		var objForm = $('#queryForm').serializeJSON();
		//alert(JSON.stringify(objForm))
		for (var code in objForm){
			if (typeof(paramObj[code]) == 'undefined'){
				paramObj[code] = objForm[code];
			}
		}
		paramObj.offset = params.offset;
		paramObj.limit = params.limit;
		
		return paramObj;
	}
	
	function responseHandler(res){
		colData = res;
		var total = colData.total;
		var dataList = colData.rows;
		var dataArray = [];
		if (dataList){
	   		 var row = null;
	   		 $.each(dataList, function(i,dataMap){  
	       		 row = {};
	       		 for (var key in dataMap){ 
	       			 xflag = 0;
	       			 for (var i in linkItem){
	       			 	if (linkItem[i] == key){
	       			 		//row[key] = "<a class='linkClass' style＝'cursor:pointer' data-toggle='modal' data-target='#myModal' name='"+key+"'>"+dataMap[key]+"</a>";
	       			 		row[key] = "<a>"+dataMap[key]+"</a>";
	       			 		xflag = 1;
	       			 		break;
	       			 	} 
	       			 }
	       			 if (xflag == 0){
	       				 row[key] = dataMap[key];
	       			 }
	       		 }
	       		dataArray.push(row);
		    });
   		}
		var retObj = new Object();
		retObj.total = total;
		retObj.rows = dataArray;
		mTable.bootstrapTable('hideLoading');
		return retObj;
	}
	
	function responseDrillHandler(res){
		colData = res;
		var total = colData.total;
		var dataList = colData.rows;
		var dataArray = [];
		if (dataList){
	   		 var row = null;
	   		 $.each(dataList, function(i,dataMap){  
	       		 row = {};
	       		 for (var key in dataMap){ 
	       			row[key] = dataMap[key];
	       		 }
	       		dataArray.push(row);
		    });
   		}
		var retObj = new Object();
		retObj.total = total;
		retObj.rows = dataArray;
		mTable.bootstrapTable('hideLoading');
		return retObj;
	}
	
	function totalTextFormatter(data) {
        return "<@spring.message 'report.sum'/>";  
    }

    function sumFormatter(data) {
        field = this.field;
        var total_sum = data.reduce(function(sum, row) {
            return (sum) + (row[field] || 0);
        }, 0);
        return total_sum;
    }
	
	function queryData(){
		mTable.bootstrapTable('showLoading');
		//alert("第几次查询："+flag);
		flag = flag + 1;
		$.ajax({
	        url:'/report/queryColumn',
	        type:'post',
	        contentType: 'application/json',
	        data:JSON.stringify({"reportId":reportId}),
	        dataType:'json',
	        success:function(data){
	        	columns = [];
	        	linkItem = new Array();
	        	isSum = data.isSum;
	        	reportColList = data.reportColList
	        	if (reportColList){
		        	$.each(reportColList,function(i,item){
		        		if(flag == 1){
	        				if (item.linkReport){
	            				linkItem[linkItem.length] = item.code;    				
	            			}
	        			}
		        		isHiddenx = true;
		        		if (item.isHidden == 1){
		        			isHiddenx = false;
		        		}
		        		if (isSum == 1){//总计
		        			if (i == 0){
		        				columns.push({
			                        field: item.code,                   
			                        title: item.name,
			                        visible:isHiddenx,
			                        footerFormatter:totalTextFormatter
			                    });
		        			}else {
		        				columns.push({
			                        field: item.code,                   
			                        title: item.name,
			                        visible:isHiddenx,
			                        footerFormatter:sumFormatter
			                    });
		        			}
		        		}else if(isSum == 0){//非
		        			columns.push({
		                        field: item.code,    
		                        visible:isHiddenx,
		                        title: item.name
		                    });
		        		}
		        	});
	        	}
	        	if (isSum == 1){
	        		mTable.bootstrapTable('refreshOptions',{
		        		columns:columns,
		        		showFooter:true,
		        		url:'/report/queryData'
		        	});
	        	}else {
	        		mTable.bootstrapTable('refreshOptions',{
		        		columns:columns,
		        		showFooter:false,
		        		url:'/report/queryData'
		        	});
	        	}
	        }
		});
	}
	
	function freshData(){
		mTable.bootstrapTable('showLoading');
		mTable.bootstrapTable('refreshOptions',{
			columns:columns,
			pageNumber:1,
    		url:'/report/queryData'
    	});
	}
	
	/* function queryData(){
		mTable.bootstrapTable('showLoading');
		//alert("第几次查询："+flag);
		flag = flag + 1;
		var obj = $('#queryForm').serializeJSON();
		var jsonString = JSON.stringify(obj);
		$.ajax({
	        url:'/report/queryColumnAndData',
	        type:'post',
	        contentType: 'application/json',
	        data:jsonString,
	        dataType:'json',
	        success:function(data){
	        	var reportColList = data.reportColList;
	        	var reportDataList =data.reportDataList;
	        	refreshTable(reportColList,reportDataList,mTable,0);
	        	
	        }
		});
	} */
	
	/* function refreshTable(reportColList,reportDataList,btTable,flag){
		if(flag == 0){
			linkItem = new Array();
		}		
		columns = [], datas = [];
		if (reportColList){
    		$.each(reportColList, function(i,item){  
    			if(flag == 0){
    				if (item.linkReport){
        				//item.name = "<a  data-toggle='modal' data-target=''#myModal'>"+item.name+"</a>";
        				linkItem[linkItem.length] = item.code;    				
        			}
    			}   			
    			//alert(item.name+":"+item.code)
        		columns.push({
                    field: item.code,                   
                    title: item.name,
                    sortable: true
                })
            });
    	}
    	if (reportDataList){
    		 var row = null;
    		 $.each(reportDataList, function(i,dataMap){  
        		 row = {};
        		 for (var key in dataMap){ 
        			 xflag = 0;
        			 for (var i in linkItem){
        			 	if (linkItem[i] == key){
        			 		row[key] = "<a class='linkClass' style＝'cursor:pointer' data-toggle='modal' data-target='#myModal' name='"+key+"'>"+dataMap[key]+"</a>";
        			 		xflag = 1;
        			 		break;
        			 	} 
        			 }
        			 if (xflag == 0){
        				 row[key] = dataMap[key];
        			 }
        		 }
        		 datas.push(row);
	            });
    	}
    	btTable.bootstrapTable('hideLoading');//hideLoading
    	btTable.bootstrapTable('refreshOptions',
                {
                    columns: columns,
                    data: datas,
                    detailView: false,
                    search: false,
                    showRefresh: false,
                    showColumns: false,
                    showExport: false,
                    pagination: true,
                    sidePagination: 'client',
                    pageList: [5, 10, 20]
                }
        )
        
	} */
	
    $(function () {
    	var reportId = $('#reportId').val();
    	reportId = reportId.replace(",","");
    	$('#reportId').val(reportId);
    	if (flag == 0){
    		queryData();
    	}
    	loadCharts();   	
    	$('#myModal').on('show.bs.modal', function () {    		
    		
        });

    	mTable.on('click-cell.bs.table', function (e,field, value, row, $element) {  
    		
    		modelTable.bootstrapTable('showLoading');//hideLoading
    		//alert(linkItem)
    		cellFlag = 0;
    		for (var i in linkItem){
			 	if (linkItem[i] == field){
			 		cellFlag = 1;
			 	} 
			 }
    		if (cellFlag == 0){
    			return ;
    		}
    		$('#myModal').modal('show');
    		//row. = value.substring(value.indexOf(">")+1,value.lastIndexOf("<"));
    		row.reportId = $("#reportId").val();
    		row.colunmName = field;
    		drillRequestObj = row;
    		$.ajax({
    	        url:'/report/queryDrillColumn',
    	        type:'post',
    	        contentType: 'application/json',
    	        data:JSON.stringify(row),
    	        dataType:'json',
    	        success:function(data){
    	        	/* retMap.put("reportColList", reportColList);
    	        	retMap.put("drillReportTitle", drillReport.getName());
    	        	retMap.put("isSum", drillReport.getIsSum()); */
    	        	
    	        	var drillReportTitle = data.drillReportTitle;
    	        	$("#myModalLabel").html(drillReportTitle);
    	        	var reportColList = data.reportColList;
    	        	isSum = data.isSum;
    	        	//设置列表字段
    	        	drillColumns = [];
    	        	if (reportColList){
    		        	$.each(reportColList,function(i,item){
    		        		isHiddenx = true;
    		        		if (item.isHidden == 1){
    		        			isHiddenx = false;
    		        		}
    		        		if (isSum == 1){//是
    		        			if (i == 0){
    		        				drillColumns.push({
    	    	                        field: item.code,                   
    	    	                        title: item.name,
    	    	                        visible:isHiddenx,
    	    	                        footerFormatter:totalTextFormatter
    	    	                    });
    		        			}else {
    		        				drillColumns.push({
    	    	                        field: item.code,                   
    	    	                        title: item.name,
    	    	                        visible:isHiddenx,
    	    	                        footerFormatter:sumFormatter
    	    	                    });
    		        			}
    		        		}else if(isSum == 0){//非
    		        			drillColumns.push({
        	                        field: item.code, 
        	                        visible:isHiddenx,
        	                        title: item.name
        	                    });
    		        		}
    		        	});
    	        	}
    	        	if (isSum == 1){
    	        		modelTable.bootstrapTable('refreshOptions',{
        	        		columns:drillColumns,
        	        		showFooter:true,
        	        		url:'/report/queryDrillData'
        	        	});
    	        	}else {
    	        		modelTable.bootstrapTable('refreshOptions',{
        	        		columns:drillColumns,
        	        		showFooter:false,
        	        		url:'/report/queryDrillData'
        	        	});
    	        	}
    	        	//refreshTable(reportColList,reportDataList,modelTable,1);  
    	        }
    		});
    	});
    	$("select").change(function(){
    		selectId = $(this).attr('id');
    		options = $("option.hideOption").attr('name');
    		linkCode = $("option.hideOption").attr('code');
    		//reportId = $("#reportId").val();
    		for (var i in options){
    			if (selectId == options[i]){
    				$.ajax({
    	    	        url:'/report/queryConditionVal',
    	    	        type:'post',
    	    	        contentType: 'application/json',
    	    	        data:JSON.stringify({"reportId":$("#reportId").val(),"paramName":selectId,"paramValue":$(this).val(),"linkCode":linkCode}),
    	    	        dataType:'json',
    	    	        success:function(data){
    	    	        	$.each(data, function(i,dataMap){
    	    	        		 $("select."+linkCode).append("<option value='"+dataMap.code+"'>"+dataMap.name+"</option>");
    	    	        		
    	    		            });
    	    	        }
    	    		});
    			}
    		}
    	});

        /**for (var i = 0; i < 10; i++) {
            columns.push({
                field: 'field' + i,
                title: 'Cell' + i,
                sortable: true
            })
        }

        var row = null
        for (i = 0; i < 3; i++) {
            row = {};
            for (var j = 0; j < 10; j++) {
                row['field' + j] = i*j;
            }
            data.push(row)
        }*/
    })
    

</script>
</@layout.defaultLayout>